<template>
  <a-modal class="common-modal" :title="title" :footer="null" :width="850" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading">
      <a-form :model="formState" @validateFields="handleOk" ref="formRef" layout="vertical" class="common-modal-content">
        <a-row :gutter="24">
          <a-col :span="19">
            <div class='blue-line mb-20'>{{$t('hangManage.baseInfo')}}</div>
            <a-row>
              <a-col :span="12">
                <a-form-item :label="$t('basicData.styleNo')" name="styleNo" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: formState.userDefined, message: $t('basicData.pleaseInputStyleNo') + '!'}]">
                  <a-input v-model:value.trim="formState.styleNo" :disabled="isEdit || (!isEdit && !formState.userDefined)" :placeholder="formState.userDefined ? $t('common.pleaseInput') : $t('common.systemAutoGenerate')" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :label="$t('common.defined')" name="userDefined" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-switch v-model:checked="formState.userDefined" :disabled="isEdit" @change="onSwitchChange" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :label="$t('basicData.styleName')" name="name" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model:value.trim="formState.name" :placeholder="$t('basicData.pleaseInputStyleName')" autoComplete="off" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :label="$t('menu.basic:producttype')" name="productType" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model:value="formState.productType" allowClear :placeholder="$t('common.pleaseSelect')">
                    <a-select-option v-for="(item,i) in prodTypeList" :value="item.name" :key="i">
                      {{item.name}}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :label="$t('other.customNo')" name="customerStyleNo" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model:value.trim="formState.customerStyleNo" :placeholder="$t('other.enterCustomNo')" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :label="$t('common.startState')" name="status" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('sysManage.selectEnable') + '!' }]">
                  <a-radio-group v-model:value="formState.status" :disabled="props.isMake">
                    <a-radio v-for="(item,index) in statusList" :value="item.value" :key="index">{{item.label}}</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <div class='blue-line mb-20 mt-10'>{{$t('basicData.styleInfo')}}</div>
            <a-row  class="over-height-box">
              <a-col :span="24">
                <a-form-item :label="$t('basicData.color')" name="colorAry" :labelCol="labelCol1" :wrapperCol="wrapperCol1" :rules="[{ required: true, message: $t('other.selectColor') }]" style="flex-direction:none;">
                  <a-input-group compact>
                    <a-select v-model:value="formState.colorAry" :allowClear="!isEditMake" mode="multiple" :placeholder="$t('common.pleaseSelect')" style="width:75%;">
                      <a-select-option v-for="item in colorList" :key="item.key" :value="item.code" :disabled="disColor(item.code)">{{item.nameCodeValue}}</a-select-option>
                    </a-select>
                    <a-popconfirm placement="topRight" :ok-text="$t('common.ok')" :cancel-text="$t('common.cancel')" @confirm="onColorPopConfirm" @cancel="onPopCancel('color')">
                      <template #icon> <span></span> </template>
                      <template #title>
                        <div class="pop-confirm-box">
                          <a-form ref="colorFormRef" style="margin-left: -22px;" :model="colorFormState">
                            <a-form-item :label="$t('basicData.colorName')" name="color" :rules="[{ required: true, trigger: 'change', message: $t('basicData.pleaseInputColorName') }]">
                              <a-input v-model:value.trim="colorFormState.color" :placeholder="$t('common.pleaseInput')" allowClear :controls="false" />
                            </a-form-item>
                          </a-form>
                        </div>
                      </template>
                      <a-button>{{ $t('common.addNew') }}</a-button>
                    </a-popconfirm>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item :label="$t('basicData.size')" name="sizeAry" :labelCol="labelCol1" :wrapperCol="wrapperCol1" :rules="[{ required: true, message: $t('other.selectSize') }]"  style="flex-direction:none;">
                  <a-input-group compact>
                    <a-select v-model:value="formState.sizeAry" :allowClear="!isEditMake" mode="multiple" :placeholder="$t('common.pleaseSelect')" style="width:75%;">
                      <a-select-option v-for="item in sizeList" :key="item.key" :disabled="disSize(item.code)" :value="item.code">{{item.nameCodeValue}}</a-select-option>
                    </a-select>
                    <a-popconfirm placement="topRight" :ok-text="$t('common.ok')" :cancel-text="$t('common.cancel')" @confirm="onSizePopConfirm" @cancel="onPopCancel('size')">
                      <template #icon> <span></span> </template>
                      <template #title>
                        <div class="pop-confirm-box">
                          <a-form ref="sizeFormRef" style="margin-left: -22px;" :model="sizeFormState">
                            <a-form-item :label="$t('basicData.size')" name="size" :rules="[{ required: true, trigger: 'change', message: $t('basicData.pleaseInputSizeName') }]">
                              <a-input v-model:value.trim="sizeFormState.size" :placeholder="$t('common.pleaseInput')" allowClear :controls="false" />
                            </a-form-item>
                          </a-form>
                        </div>
                      </template>
                      <a-button>{{ $t('common.addNew') }}</a-button>
                    </a-popconfirm>
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item :label="$t('hangManage.proLocation')" :labelCol="labelCol1" :wrapperCol="wrapperCol1">
                  <part-table ref="partTable" :partList="partList" :tableData="partNameList" @addType="addType" @deleteType="deleteType" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item :label="$t('common.remark')" name="remark" :labelCol="labelCol1" :wrapperCol="wrapperCol1">
                  <a-textarea v-model:value.trim="formState.remark" :placeholder="$t('common.pleaseInput')" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="5">
            <a-form-item :label="$t('hangManage.img')" :labelCol="{span: 24}" :wrapperCol="{span: 24}" class="upload-item">
              <a-upload v-model:fileList="fileList" :action="uploadUrl" :headers="uploadHeader" list-type="picture-card" @change="handleUploadImg" @preview="(file) => handlePreviewToggle(true, file)" :before-upload="beforeImgUpload">
                <div v-if="fileList.length == 0">
                  <plus-outlined></plus-outlined>
                  <div class="ant-upload-text">{{ $t('other.uploadImage') }}</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{$t('common.cancel')}}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{$t('common.ok')}}</a-button>
      </div>
    </a-spin>
    <a-modal :visible="previewVisible" :title="$t('other.viewPic')" :footer="null" @cancel="() => handlePreviewToggle(false)">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-modal>
</template>

<script setup name="operateModal">
import { nextTick, onMounted, ref, computed, watch } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue'
import { uploadUrl } from '@/api/commonApi'
import axios from '@/utils/request'
import { cloneDeep, uniqBy } from 'lodash'
import PartTable from './partTable.vue'
import { beforeImgUpload, handleUploadImg, getToken } from '@/utils'
import { store } from '@/store'
import i18n from '@/locales/index' 
const { t } = i18n.global
const emits = defineEmits(['ok'])
const props = defineProps({
  isMake: {
    type: Boolean,
    default: () => false
  }
})
const labelCol = { xs: { span: 24 }, sm: { span: 22 } }
const wrapperCol = { xs: { span: 24 }, sm: { span: 22 } }
const labelCol1 = { xs: { span: 24 }, sm: { span: 23 } }
const wrapperCol1 = { xs: { span: 24 }, sm: { span: 23 } }
let title = ref('')
let visible = ref(false)
let isEdit = ref(false)
let confirmLoading = ref(false)
let statusList = [
  { value: 0, label: t('common.start') },
  { value: 1, label: t('common.stop') }
]
let recordInfo = ref({})
let formState = ref({})
const formRef = ref()
let partNameList = ref([])
let previewVisible = ref(false)
let previewImage = ref('')
let fileList = ref([])
let colorFormRef = ref()
let sizeFormRef = ref()
let colorFormState = ref({})
let sizeFormState = ref({})
let isEditMake = ref(false)
const colorList = ref([])
const sizeList = ref([])
const usedColorAry = ref([])
const usedSizeAry = ref([])
const colorBaseAry = computed(() => {
  (store.state.normalData.colorList || []).forEach(i => { i.nameCodeValue = `${i.name}-${i.code}` })
  return store.state.normalData.colorList
})
const sizeBaseAry = computed(() => {
  (store.state.normalData.sizeList || []).forEach(i => { i.nameCodeValue = `${i.name}-${i.code}` })
  return store.state.normalData.sizeList
})
const partList = computed(() => {
  return store.state.normalData.partList
})
const prodTypeList = computed(() => {
  return store.state.normalData.prodTypeList
})

let uploadHeader = ref({
  Authorization: getToken()
})
const edit = async (record, editable, isMakeEdit = false) => {
  initModalData(record, editable)
  isEditMake.value = isMakeEdit
  if (props.isMake) record.status = 0
  await nextTick()
  if (!record.id) {
    record.status = 0
  }
  formRef.value.resetFields()
  formState.value = cloneDeep(record)
}
const disColor = (code) => {
  if (isEditMake.value) return recordInfo.value.styleColorList.map(i => i.colorCode).includes(code)
}
const disSize = (code) => {
  if (isEditMake.value) return recordInfo.value.styleSizeList.map(i => i.sizeCode).includes(code)
}
const initOpt = () => {
  colorList.value = uniqBy(colorBaseAry.value.concat(usedColorAry.value), 'code')
  sizeList.value = uniqBy(sizeBaseAry.value.concat(usedSizeAry.value), 'code')
}
const initBaseOpt = (styleColorList, styleSizeList) => {
  styleColorList.forEach(i => { i.name = i.color; i.code = i.colorCode; i.nameCodeValue = `${i.name}-${i.code}` })
  styleSizeList.forEach(i => { i.name = i.size; i.code = i.sizeCode; i.nameCodeValue = `${i.name}-${i.code}` })
  usedColorAry.value = styleColorList
  usedSizeAry.value = styleSizeList
}
const initModalData = (record, editable) => {
  title.value = `${record.id ? t('common.edit') : t('common.addNew')} ${t('basicData.style')}`
  let { productPartNameList, styleSizeList, styleColorList, url } = record
  partNameList.value = productPartNameList && productPartNameList.length ? productPartNameList.map(item => ({
    name: item,
    id: Math.random()
  })) : [{ id: Math.random(), name: undefined }]

  initBaseOpt(styleColorList || [], styleSizeList || [])
  initOpt()
  record.sizeAry = (styleSizeList || []).map(i => i.sizeCode)
  record.colorAry = (styleColorList || []).map(i => i.colorCode)
  if (url) fileList.value = [{ uid: '-1', url }]
  recordInfo.value = Object.assign({}, record)
  visible.value = true
  isEdit.value = editable
}
const queryParams = (value) => {
  const params = cloneDeep(value)
  params.url = fileList.value.length ? fileList.value[0].response ? fileList.value[0].response.data : fileList.value[0].url : null
  params.id = recordInfo.value.id
  params.productPartNameList = partNameList.value.filter(item => item.name).map(item => item.name)
  params.styleColorList = colorList.value.filter(el => formState.value.colorAry.includes(el.code)).map(i => {
    i.color = i.name
    i.colorCode = i.code
    delete i.id
    return i
  })
  params.styleSizeList = sizeList.value.filter(el => formState.value.sizeAry.includes(el.code)).map(i => {
    i.size = i.name
    i.sizeCode = i.code
    delete i.id
    return i
  })
  return params
}
const handleOk = async () => {
  try {
    await formRef.value.validateFields();
    confirmLoading.value = true
    let url = recordInfo.value.id ? '/api/basic/style/edit' : '/api/basic/style/save'
    const res = await axios.postAction(url, queryParams(formState.value))
    if (res.success) {
      emits('ok', res.data)
      initModalStatus()
      visible.value = false
    }
  } catch (err) {
    console.log('0000000', err)
  }
  confirmLoading.value = false
}
const handleCancel = () => {
  visible.value = false
  initModalStatus()
}
const onSwitchChange = () => {
  formState.value.styleNo = null
}
const initModalStatus = () => {
  confirmLoading.value = false
  formState.value = {}
  formRef.value.resetFields()
  fileList.value = []
}
const addType = (value) => {
  partNameList.value.push(value);
}
const deleteType = (id) => {
  const dataList = partNameList.value.filter(item => item.id !== id)
  partNameList.value = dataList
}
const handlePreviewToggle = (value, file) => {
  if (value) {
    if (file.response && file.response.data) {
      previewImage.value = file.response.data
    } else if (file.url) {
      previewImage.value = file.url
    }
  }
  previewVisible.value = value
}
const onColorPopConfirm = async () => {
  const value = await colorFormRef.value.validateFields()
  if (value) {
    let res = await axios.postAction('/api/basic/color/save', { status: 0, name: colorFormState.value.color })
    if (res.success) {
      await store.dispatch('getColor')
      formState.value.colorAry.push(res.data)
      colorFormState.value = {}
      formRef.value.clearValidate('colorAry')
    }
  }
}
const onSizePopConfirm = async () => {
  const value = await await sizeFormRef.value.validateFields()
  if (value) {
    let res = await axios.postAction('/api/basic/size/save', { status: 0, name: sizeFormState.value.size })
    if (res.success) {
      await store.dispatch('getSize')
      formState.value.sizeAry.push(res.data)
      sizeFormState.value = {}
      formRef.value.clearValidate('sizeAry')
    }
  }
}
const onPopCancel = async (type) => {
  type == 'color' ? colorFormRef.value.clearValidate() : sizeFormRef.value.clearValidate()
  colorFormState.value = {}
  sizeFormState.value = {}
}
watch(() => colorBaseAry.value, () => {
  initOpt()
}, { deep: true, immediate: true })
watch(() => sizeBaseAry.value, () => {
  initOpt()
}, { deep: true, immediate: true })
onMounted(async () => {
  await store.dispatch('getColor')
  await store.dispatch('getSize')
  await store.dispatch('getPart')
  await store.dispatch('getProdType')
})
defineExpose({
  edit
})

</script>